package br.com.transitojp.dao;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;

/**  
 * HibernateSessionRequestFilter.java - this class is resposible for the loggin on Sessions.  
 * @author LAViD - Laboratório de Aplicação de Vídeo Digital.
 * @version 1.0 
 */
public class HibernateSessionRequestFilter implements Filter {
	 
	private static Log log = LogFactory.getLog(HibernateSessionRequestFilter.class);

    private SessionFactory sf = HibernateUtil.getSessionFactory();

    /**  
	 * The purpose of this method is to log what happens when this method is called.  
	 * @return no return.  
	 */
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {

       try {
    	   
    	   log.debug("Starting a database transaction");
	       sf.getCurrentSession().beginTransaction();
	       chain.doFilter(request, response);
	       log.debug("Committing the database transaction");
	       sf.getCurrentSession().getTransaction().commit();

       } catch (StaleObjectStateException staleEx) {

        	log.error("This interceptor does not implement optimistic concurrency control!");
            log.error("Your application will not work until you add compensation actions!");
	        throw staleEx;
	  
       } catch (Throwable ex) {
	   
    	   ex.printStackTrace();
	       
    	   try {
	       
    		   if (sf.getCurrentSession().getTransaction().isActive()) {
    			   log.debug("Trying to rollback database transaction after exception");
	               sf.getCurrentSession().getTransaction().rollback();
	           		}
	            } catch (Throwable rbEx) {
                
	            	log.error("Could not rollback transaction after exception!", rbEx);
	            
	            }

	            throw new ServletException(ex);
	        }
	    
    }

    /**  
	 * The purpose of this method is to print those lines on the log when this class is initialized.
	 * @return no return.  
	 */
    public void init(FilterConfig filterConfig) throws ServletException {
    	
    	log.debug("Initializing filter...");
        log.debug("Obtaining SessionFactory from static HibernateUtil singleton");
	    sf = HibernateUtil.getSessionFactory();
	
    }

    /**  
	 * This method is needed because this class extends Filter..
	 * @return A User data type.  
	 */
    public void destroy() {}

}